import mainApi from '@/api/main'
import constantRoutes from '@/router/router'
import constant from '@/utils/constant'
import session from '@/utils/session'

const main = {
    namespaced: true,
    state: {
        activeTab: constant.ConstantRouteName.Home,
        tabs: [{label: "首页", name: constant.ConstantRouteName.Home}],
        menus: [],
        dynRoutes: [],
        routes: []
    },
    getters: {},
    mutations: {
        setActiveTab(state, activeTab) {
            state.activeTab = activeTab;
        },
        addTabs(state, tabObj) {
            let noTab = true;
            let tabName = tabObj.name;
            state.tabs.forEach((item, index) => {
                if (item.name == tabName) {
                    noTab = false;
                }
            });
            if (noTab) {
                state.tabs.push({
                    label: tabObj.title,
                    name: tabObj.name
                });
            }
            state.activeTab = tabName;
        },
        removeTabs(state, tabName) {
            let activeName = state.activeTab;
            if (activeName === tabName) {
                state.tabs.forEach((item, index) => {
                    if (item.name === tabName) {
                        let nextTab = state.tabs[index + 1] || state.tabs[index - 1];
                        if (nextTab) {
                            state.activeTab = nextTab.name;
                        }
                    }
                });
            }
            state.tabs = state.tabs.filter(item => item.name !== tabName);
        },
        setMenus(state, menus) {
            state.menus = menus;
        },
        setRoutes(state, {routes = [], dynRoutes = []}) {
            state.dynRoutes = dynRoutes;
            state.routes = routes;
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
        }
    },
    actions: {
        async createRoutes({commit, state}) {
            let menuNodes = [];
            let routeNodes = [];
            let routes = [];
            await mainApi.doMenu().then(result => {
                let menus = result.bean;
                if(!Array.isArray(menus)) {
                    return Promise.reject("获取菜单信息失败，请重新登陆");
                }

                // 创建菜单和路由
                menuNodes = createMnus(menus);
                routeNodes = createRoutes(menuNodes);

                // 初始化默认路由
                let defaultRoute = {
                    path: '*',
                    redirect: "/404",
                };
                routeNodes.push(defaultRoute);;

                // 设置菜单和路由
                commit("setMenus", menuNodes);
                let routes = [...constantRoutes, ...routeNodes];
                commit("setRoutes", { routes: routes, dynRoutes: routeNodes});
            }).catch(error => {
                return Promise.reject("获取菜单信息异常，请重新登陆");
            });
            return {routes, dynRoutes: routeNodes };

        }
    }
};

function createMnus(nodes) {
    let menuNodes = [];
    nodes.forEach(node => {
        let menuNode = {
            path: node.code,
            name: node.code,
            fullPath: node.code,
            initPageName: node.path,
            initName: node.code,
            initPath: node.code,
            icon: node.icon,
            title: node.name,
            level: 0,
            children: []
        }
        if(node.children && node.children.length > 0) {
            doCreateMenus({rootNode:node, rootMenuNode:menuNode});
        } else {
            menuNode.name = "_" + menuNode.initName;
            menuNode.path = "index";
            menuNode.fullPath = menuNode.fullPath + "/index";
        }
        menuNodes.push(menuNode);
    });
    return menuNodes;
}

function doCreateMenus({rootNode, rootMenuNode}) {
    let nodes = rootNode.children;
    if(nodes&&nodes.length > 0) {
        nodes.forEach(node => {
            let menuNode = {
                path: node.code,
                name: node.code,
                fullPath: rootMenuNode.fullPath + "/" + node.code,
                initPageName: node.path,
                initName: node.code,
                initPath: node.code,
                title: node.name,
                icon: node.icon,
                level: rootMenuNode.level+1,
                children: []
            }
            doCreateMenus({rootNode:node, rootMenuNode:menuNode});
            rootMenuNode.children.push(menuNode);
        });
    }
}

function createRoutes(nodes) {
    let routeNodes = [];
    nodes.forEach(node => {
        let routeNode = {
            path: "/"+node.initPath,
            name: node.initName,
            component: () => import('@/views/main/index'),
            meta: {
                title: node.title,
                icon: node.icon
            },
            children: []
        };
        doCreateRoutes({rootNode: node, rootRouteNode: routeNode});
        routeNodes.push(routeNode);
    });
    return routeNodes;
}

function doCreateRoutes({rootNode, rootRouteNode}) {
    if(!rootNode.children || rootNode.children.length <= 0) {
        let routeNode = {
            path: rootNode.fullPath.substr(rootNode.fullPath.indexOf("/")+1, rootNode.fullPath.length),
            name: rootNode.name,
            component: () => import('@/views/'+rootNode.initPageName+'/index'),
            meta: {
                title: rootNode.title,
                icon: rootNode.icon,

            },
            children: []
        };
        rootRouteNode.children.push(routeNode)
    } else {
        for(let index in rootNode.children) {
            doCreateRoutes({rootNode: rootNode.children[index], rootRouteNode});
        }
    }
}

export default main;

